import React, { memo, useCallback, useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { Carousel } from 'antd';

import { getTopBannerAction } from '../../store/actionCreators';

import { BannerWrapper, BannerLeft, BannerRight, BannerControl } from './style'

const banner = memo(() => {
    const bannerRef = useRef()
    const [current, setCurrent] = useState(0)

    const dispatch = useDispatch()
    //  shallowEqual 将数据进行浅层比较，未改变将不会重新渲染页面，提高性能
    const { banners } = useSelector(state => ({
        // banners: state.get('recommend').get('banners')
        banners: state.getIn(['recommend', 'banners'])
    }), shallowEqual)

    useEffect(() => {
        dispatch(getTopBannerAction())
    }, [dispatch])

    const beforeChange = useCallback((from, to) => {
        setTimeout(() => {
            setCurrent(to);
        }, 0);
    }, [])
    const bgImg = banners[current] && banners[current].imageUrl + "?imageView&blur=40x20"

    return (
        <BannerWrapper bgImg={bgImg}>
            <div className="banner wrap-v2">
                <BannerLeft>
                    <Carousel effect="fade" autoplay ref={bannerRef} beforeChange={beforeChange}>
                        {
                            banners.map(item => {
                                return (
                                    <div className='banner-item' key={item.imageUrl}>
                                        <img className='image' src={item.imageUrl} alt={item.typeTitle} />
                                    </div>
                                )
                            })
                        }
                    </Carousel>
                </BannerLeft>
                <BannerRight />
                <BannerControl>
                    <button className="btn left" onClick={e => bannerRef.current.prev()}></button>
                    <button className="btn right" onClick={e => bannerRef.current.next()}></button>
                </BannerControl>
            </div>
        </BannerWrapper>
    )
})

export default banner